<template>
  <div class="form-item-el">
    <div v-if="mode === 'DESIGN'">
      <el-button disabled :icon="User" type="primary" size="small" round>选择人员</el-button>
      <span class="placeholder"> {{ placeholder }}</span>
    </div>
    <div v-else-if="mode === 'PC' && !readonly" style="max-width: 350px">
      <el-button v-if="!$attrs.disabled" :icon="User" type="primary" size="small" round @click="$refs.orgPicker.show()"
        >选择人员</el-button
      >
      <org-picker type="user" :multiple="multiple" ref="orgPicker" :selected="_value" @ok="selected" />
      <span class="placeholder" v-if="!_value.length"> {{ placeholder }}</span>
      <div style="margin-top: 5px">
        <el-tag
          size="small"
          style="margin: 5px"
          v-for="(dept, i) in _value"
          :key="dept.id"
          @close="delDept(i)"
          :closable="!$attrs.disabled"
          >{{ dept.name }}</el-tag
        >
      </div>
    </div>
    <div v-else class="preview">
      <AvatarView :size="35" :name="user.name" showY :src="user.avatar" v-for="user in _value" :key="user.id" />
    </div>
  </div>
</template>

<script setup>
import { computed, ref, useAttrs } from "vue";
import { User } from "@element-plus/icons-vue";
import _ from "lodash";
import OrgPicker from "../OrgPicker/index.vue";
import AvatarView from "../AvatarView";

const props = defineProps({
  mode: {
    type: String,
    default: "DESIGN"
  },
  required: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: "请选择人员"
  },
  multiple: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(["update:modelValue"]);
const $attrs = useAttrs();
const _value = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const deptDesc = computed({
  get() {
    if (_value.value && _value.value.length > 1) {
      return `${_value.value[0].name}${_value.value[1].name}..等${_value.value.length}人`;
    } else if (_value.value && _value.value.length > 0) {
      return _value.value[0].name;
    } else {
      return null;
    }
  },
  set() {}
});

const showOrgSelect = ref(false);

const selected = values => {
  showOrgSelect.value = false;
  _value.value = values;
};
const delDept = i => {
  _value.value.splice(i, 1);
};

if (_.isEmpty(_value.value) && !$attrs.disabled) {
  _value.value = $attrs.defaultValue;
}
</script>

<style scoped lang="scss">
.placeholder {
  margin-left: 10px;
  color: #adabab;
  font-size: smaller;
}
.preview {
  display: flex;
  justify-content: left;
  :deep(.avatar) {
    margin: 0 5px;
  }
}
</style>
